import csv

from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .models import PayMain, PayDetail
from .forms import PayMainForm, PayDetailForm


def pay_main_list(request):
    pays = PayMain.objects.all()
    print(pays)
    return render(request, 'pay-main-list.html', {'pay_mains': pays})


def export_pay_main_csv(request):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename="pay_main.csv"'

    # 采购数据的字段名，中文表头
    field_names = ['采购清单', '员工编号', '采购数量', '采购总价', '采购时间', '备注']

    # 写入 CSV 文件
    writer = csv.writer(response, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([name for name in field_names])  # 写入表头

    # 获取所有采购数据
    pay_mains = PayMain.objects.all()

    # 将采购数据写入 CSV 文件
    for pay_main in pay_mains:
        writer.writerow([
            pay_main.Pid,
            pay_main.Eid,
            pay_main.Pcount,
            pay_main.Ptotal,
            pay_main.Pdate,
            pay_main.other,
        ])

    # 设置 UTF-8 with BOM 编码格式
    response.write('\ufeff'.encode('utf-8'))

    return response


def pay_main_add(request):
    if request.method == 'POST':
        form = PayMainForm(request.POST)
        if form.is_valid():
            form.save()
            return JsonResponse({'code': 200, 'message': '采购主表添加成功'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    else:
        form = PayMainForm()
    return render(request, 'pay-main-add.html', {'form': form})


def pay_main_update(request, pid):
    pay = PayMain.objects.get(Pid=pid)
    if request.method == 'POST':
        form = PayMainForm(request.POST, instance=pay)
        if form.is_valid():
            form.save()
            return JsonResponse({'code': 200, 'message': '采购主表更新成功'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    else:
        form = pay
    return render(request, 'pay-main-update.html', {'pay_main': form})

@csrf_exempt
def pay_main_delete(request, Pid):
    pay = PayMain.objects.get(Pid=Pid)
    pay.delete()
    return JsonResponse({'code': 200, 'message': '采购主表删除成功'})


def pay_detail_list(request, Pid):
    pay_main = get_object_or_404(PayMain, Pid=Pid)
    pay_details = PayDetail.objects.filter(Pid=Pid)
    return render(request, 'pay-detail-list.html', {'pay_main': pay_main, 'pay_details': pay_details})


def pay_detail_add(request, Pid):
    if request.method == 'POST':
        form = PayDetailForm(request.POST)
        if form.is_valid():
            Pcount = form.cleaned_data['Pcount']
            GPay = form.cleaned_data['GPay']
            total = Pcount * GPay
            pay_detail = form.save(commit=False)
            pay_detail.total = total
            pay_detail.save()
            return JsonResponse({'code': 200, 'message': '采购明细添加成功', 'Pid': Pid})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    return render(request, 'pay-detail-add.html', {'Pid': Pid})


def pay_detail_update(request, PDid):
    if request.method == 'POST':
        pay_detail = PayDetail.objects.get(PDid=PDid)
        form = PayDetailForm(request.POST, instance=pay_detail)
        if form.is_valid():
            Pcount = form.cleaned_data['Pcount']
            GPay = form.cleaned_data['GPay']
            total = Pcount * GPay
            form.instance.total = total
            form.save()
            return JsonResponse({'code': 200, 'message': '采购明细更新成功'})
        else:
            return JsonResponse({'code': 400, 'message': '表单数据不合法'})
    else:
        pay_detail = PayDetail.objects.get(PDid=PDid)
        form = PayDetailForm(instance=pay_detail)
    return render(request, 'pay-detail-update.html', {'form': form, 'PDid': PDid})


@csrf_exempt
def pay_detail_delete(request, PDid):
    try:
        pay_detail = PayDetail.objects.get(PDid=PDid)
        pay_detail.delete()
        return JsonResponse({'code': 200, 'message': '采购明细删除成功'})
    except PayDetail.DoesNotExist:
        return JsonResponse({'code': 404, 'message': '采购明细不存在'})
